package com.invest.infra.template;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.Date;

/**
 * STMS 2012
 * 
 * @author Evan
 * @date 2012-09-15
 * 
 */
public class TemplateUtils {
	
	private static final String DEFAULT_ENCODING = "UTF-8";
	private static final Configuration FILE_CFG = new Configuration();
	static{
		initCfg(FILE_CFG);
	}
	
	private static void initCfg(Configuration cfg){
		cfg.setNumberFormat("0.######");
		cfg.setDefaultEncoding(DEFAULT_ENCODING);
		cfg.setClassForTemplateLoading(TemplateUtils.class, "/");
	}
	
	/**
	 * get template content
	 * @param templateName
	 * @param model
	 * @return
	 */
	public static <T> String getFileTmpContent(String templateName,T model) {
		
		String content = null;
		try {
			Template template = FILE_CFG.getTemplate(templateName);
			content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
			
		} catch (TemplateException e) {
			throw new RuntimeException(e);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return content;
	}
	
	public static  <T> String getStrTmpContent(String tmpContent,T model) {
		
		String content = "";
		try {
			
				final String tmpName = "strTmp" + new Date().getTime();
		        StringTemplateLoader strLoader = new StringTemplateLoader();  
		        strLoader.putTemplate(tmpName,tmpContent);  
		        
		        Configuration cfg = new Configuration(); 
				initCfg(cfg);
		        cfg.setTemplateLoader(strLoader);  
		        Template template = cfg.getTemplate(tmpName,"utf-8");  
		        content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
			    
		} catch (TemplateException e) {
			throw new RuntimeException(e);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return content;
	}
}
